import React, { useState, Fragment, useEffect } from 'react'
import { Tag, Input, Modal, Button, Form, Card, Avatar, message } from "antd";
import { PageHeaderWrapper } from "@ant-design/pro-layout";
import { PlusSquareOutlined, MinusSquareOutlined, ExclamationCircleOutlined, MobileOutlined, DesktopOutlined } from '@ant-design/icons';
import styles from './index.less'
import request from '@/utils/request';
import Save from './save'
const { confirm } = Modal;

const separator = '|———';
export default () => {
    const [modalVisable, setModalVisable] = useState(false)
    const [tableData, setTableData] = useState([])
    const [info, setInfo] = useState({ id: 0, pid: 0 });
    const [form] = Form.useForm();

    const Deep = (deepProps: any) => {
        return (
            deepProps.items.map((item: any) => {
                const keyList = item.key.split("-");
                let topVisable;
                tableData.forEach((data: any) => {
                    if (data.id == keyList[0]) {
                        topVisable = data.show
                    }
                });

                return (
                    <Fragment key={item.key}>
                        {/* 顶级 是隐藏标识 且 不是顶级本身 */}
                        <tr style={keyList.length > 1 && (!topVisable) ? { display: "none" } : {}} >
                            <td>
                                {
                                    keyList.length == 1 ?
                                        <span style={{ width: "25px", display: "inline-block" }}>
                                            {(topVisable ? <MinusSquareOutlined onClick={() => {
                                                const result: any = tableData.map((val: any) => {
                                                    let newVal = { ...val };
                                                    val.id == item.id && (newVal.show = false)
                                                    return newVal
                                                });
                                                setTableData(result)
                                            }} /> : <PlusSquareOutlined onClick={() => {
                                                const result: any = tableData.map((val: any) => {
                                                    let newVal = { ...val };
                                                    val.id == item.id && (newVal.show = true)
                                                    return newVal
                                                });
                                                setTableData(result)
                                            }} />)}
                                        </span> :
                                        <span style={{ color: "#ccc", marginLeft: `25px` }}>{separator.repeat(keyList.length - 1)}</span>
                                }
                                <Input style={{ width: "200px" }} value={item.name} />
                                {
                                    keyList.length < 3 &&
                                    <Tag color="green" style={{ marginLeft: "8px", cursor: "pointer" }} onClick={() => {
                                        form.resetFields()
                                        setInfo({ id: 0, pid: item.id })
                                        setModalVisable(true)
                                    }}>新增</Tag>
                                }
                            </td>
                            <td><Input value={item.short_name} /></td>
                            <td style={{ textAlign: "center" }}>
                                <DesktopOutlined />
                                <MobileOutlined />
                            </td>
                            <td style={{ textAlign: "center" }}><Avatar src="https://avatars.dicebear.com/v2/male/dad.svg" /></td>
                            <td style={{ textAlign: "center" }}>关联类型</td>
                            <td style={{ textAlign: "center" }}>
                                <Tag color="blue">是</Tag>
                            </td>
                            <td style={{ textAlign: "center" }}>
                                <Tag color="cyan">10</Tag>
                            </td>
                            <td style={{ textAlign: "center" }}>
                                <Button size="small" type="primary" ghost style={{ marginRight: "5px" }} onClick={() => {
                                    setModalVisable(true)
                                    setInfo({ id: item.id, pid: 0 })
                                    request(`/goods/category/${item.id}`).then((result) => {
                                        let data = result.data;
                                        data.upload = [];
                                        if (data.logo) {
                                            data.upload = [{
                                                uid: new Date().getTime(),
                                                name: data.logo.substr(-15, 15),
                                                url: data.logo
                                            }];
                                        }
                                        form.setFieldsValue(data)
                                    })
                                }}>修改</Button>
                                <Button size="small" danger onClick={() => {
                                    destroy(item.id)
                                }}>删除</Button>
                            </td>
                        </tr>
                        {item.children?.length > 0 && <Deep items={item.children} />}
                    </Fragment>
                );
            })
        );
    }


    const destroy = (id: number) => {
        confirm({
            title: 'Do you Want to delete these items?',
            icon: <ExclamationCircleOutlined />,
            onOk() {
                request(`/goods/category/${id}`, {
                    method: "Delete"
                }).then((result: any) => {
                    if (result.code === 200) {
                        message.success("删除成功")
                        getTree();
                    }
                })
            }
        });
    }

    const getTree = () => {
        request('/goods/category-tree').then((result) => {
            const hideIds: any[] = [];
            tableData.forEach((item: any) => {
                if (item.show) {
                    hideIds.push(item.id)
                }
            })
            const res = result.data.map((item: any) => {
                return { ...item, show: hideIds.includes(item.id) };
            });
            console.log(res)
            setTableData(res);
        })
    }
    useEffect(() => {
        getTree()
    }, [])

    return (
        <PageHeaderWrapper title={false}>
            <Card title={<Button onClick={() => {
                form.resetFields()
                setInfo({ id: 0, pid: 0 })
                setModalVisable(true)
            }}>添加分类</Button>}>
                <table style={{ width: "100%" }}>
                    <thead>
                        <tr>
                            <th style={{ width: "32%" }}>分类名称</th>
                            <th style={{ width: "200px" }}>商品分类简称</th>
                            <th style={{ textAlign: "center" }}>复制链接</th>
                            <th style={{ textAlign: "center" }}>图片</th>
                            <th style={{ textAlign: "center" }}>关联类型</th>
                            <th style={{ textAlign: "center" }}>是否显示</th>
                            <th style={{ textAlign: "center" }}>排序</th>
                            <th style={{ textAlign: "center" }}>操作</th>
                        </tr>
                    </thead>
                    <tbody className={styles.tbody}>
                        <Deep items={tableData} />
                    </tbody>
                </table>
                <Modal
                    width="40%"
                    title="保存分类"
                    visible={modalVisable}
                    onOk={() => {
                        form.submit()
                    }}
                    onCancel={() => {
                        setModalVisable(false)
                    }}
                    getContainer={false}
                >
                    <Save form={form} close={() => {
                        setModalVisable(false)
                    }} info={info} getTree={getTree} />
                </Modal>
            </Card>
        </PageHeaderWrapper>
    );
};
